﻿<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>多张图片上传插件</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="../css/common.css"/>
    <script src="../js/jquery-3.4.1.js"></script>
    <style>
        .inner {
            width: 100%;
            margin: 0 auto;
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
        }

        .problem {
            width: 100%;
        }

        #userName, #userMobile {
            width: 250px;
            height: 35px;
        }
    </style>

</head>
<body style="height: 100vh;background-color: #EEF5FD;">
<div class="inner">
    <div class="problem">
        <div class="custom_img">
            <div class="custom_img_top">
                <h5>图片说明</h5>
                <h5><span class="upload_img_length">0</span>/8</h5>
            </div>
            <div style="height: 80px;width: 100%;background-color: green;top: 20px;position: absolute">
                <form id="textFrom">
                    <table style="color:white;">
                        <tr>
                            <td><label for="userName">用户姓名</label></td>
                            <td><input type="text" id="userName" name="userName" value="张三"></td>
                        </tr>
                        <tr>
                            <td><label for="userName">手机号</label></td>
                            <td><input type="text" id="userMobile" name="userMobile" value="18891999988"></td>
                        </tr>
                    </table>
                </form>
            </div>
            <!--点击上传图片 触发下面的div 点击事件-->
            <div class="upload_img_wrap">
                <div id="imgBox"></div>
                <img class="upload_img" data-id="1" src="../img/upload_img.png"/>
                <img style="display:none" class="upload_img" data-id="2" src="../img/upload_img.png"/>
                <img style="display:none" class="upload_img" data-id="3" src="../img/upload_img.png"/>
                <img style="display:none" class="upload_img" data-id="4" src="../img/upload_img.png"/>
                <img style="display:none" class="upload_img" data-id="5" src="../img/upload_img.png"/>
                <img style="display:none" class="upload_img" data-id="6" src="../img/upload_img.png"/>
                <img style="display:none" class="upload_img" data-id="7" src="../img/upload_img.png"/>
                <img style="display:none" class="upload_img" data-id="8" src="../img/upload_img.png"/>
            </div>
            <div style="display: none;width: 100%;height: 100vh;position: relative;">
                <form id="upBox" class="upload_form" action="" method="post" enctype="multipart/form-data">
                    <div style="display: none;" id="inputBox">
                        <input type="file" name="image" data-id="1" title="请选择图片" id="file1"
                               accept="image/png,image/jpg,image/gif,image/JPEG"/>
                        <input type="file" name="image" data-id="2" title="请选择图片" id="file2"
                               accept="image/png,image/jpg,image/gif,image/JPEG"/>
                        <input type="file" name="image" data-id="3" title="请选择图片" id="file3"
                               accept="image/png,image/jpg,image/gif,image/JPEG"/>
                        <input type="file" name="image" data-id="4" title="请选择图片" id="file4"
                               accept="image/png,image/jpg,image/gif,image/JPEG"/>
                        <input type="file" name="image" data-id="5" title="请选择图片" id="file5"
                               accept="image/png,image/jpg,image/gif,image/JPEG"/>
                        <input type="file" name="image" data-id="6" title="请选择图片" id="file6"
                               accept="image/png,image/jpg,image/gif,image/JPEG"/>
                        <input type="file" name="image" data-id="7" title="请选择图片" id="file7"
                               accept="image/png,image/jpg,image/gif,image/JPEG"/>
                        <input type="file" name="image" data-id="8" title="请选择图片" id="file8"
                               accept="image/png,image/jpg,image/gif,image/JPEG"/> 点击选择图片
                    </div>
                </form>
            </div>
        </div>
        <button class="custom_sub" onclick="doUpload()" id="btn">提交上传</button>
    </div>
</div>
<script>
    var indexSet = new Array(8);
    var imgNum = 0;
    $(".upload_img_wrap .upload_img").bind("click", function (ev) {
        console.log(ev.currentTarget.dataset.id);
        var index = ev.currentTarget.dataset.id;
        var that = this;
        if (index == 1) {
            $("#file1").click();
            $("#file1").unbind().change(function (e) {
                var index = e.currentTarget.dataset.id;
                if ($('#file1').val() == '') {
                    return false;
                }
                $(that).hide();
                var filePath = $(this).val();
                changeImg(e, filePath, index);

                imgNum++;
                if (imgNum < 8) {
                    $(".upload_img").eq(1).show();
                }
                $(".upload_img_length").html(imgNum);
            })
        } else if (index == 2) {
            $("#file2").click();
            $("#file2").unbind().change(function (e) {
                var index = e.currentTarget.dataset.id;
                if ($('#file2').val() == '') {
                    return false;
                }
                ;
                $(that).hide();
                var filePath = $(this).val();
                changeImg(e, filePath, index);

                imgNum++;
                if (imgNum < 8) {
                    $(".upload_img").eq(2).show();
                }
                $(".upload_img_length").html(imgNum);
            })
        } else if (index == 3) {
            $("#file3").click();
            $("#file3").unbind().change(function (e) {
                var index = e.currentTarget.dataset.id;
                if ($('#file3').val() == '') {
                    return false;
                }
                20
                $(that).hide();
                var filePath = $(this).val();
                changeImg(e, filePath, index);

                imgNum++;
                if (imgNum < 8) {
                    $(".upload_img").eq(3).show();
                }
                $(".upload_img_length").html(imgNum);
            })
        } else if (index == 4) {
            $("#file4").click();
            $("#file4").unbind().change(function (e) {
                var index = e.currentTarget.dataset.id;
                if ($('#file4').val() == '') {
                    return false;
                }
                20
                $(that).hide();
                var filePath = $(this).val();
                changeImg(e, filePath, index);

                imgNum++;
                if (imgNum < 8) {
                    $(".upload_img").eq(4).show();
                }
                $(".upload_img_length").html(imgNum);
            })
        } else if (index == 5) {
            $("#file5").click();
            $("#file5").unbind().change(function (e) {
                var index = e.currentTarget.dataset.id;
                if ($('#file5').val() == '') {
                    return false;
                }
                20
                $(that).hide();
                var filePath = $(this).val();
                changeImg(e, filePath, index);

                imgNum++;
                if (imgNum < 8) {
                    $(".upload_img").eq(5).show();
                }
                $(".upload_img_length").html(imgNum);
            })
        } else if (index == 6) {
            $("#file6").click();
            $("#file6").unbind().change(function (e) {
                var index = e.currentTarget.dataset.id;
                if ($('#file6').val() == '') {
                    return false;
                }
                20
                $(that).hide();
                var filePath = $(this).val();
                changeImg(e, filePath, index);

                imgNum++;
                if (imgNum < 8) {
                    $(".upload_img").eq(6).show();
                }
                $(".upload_img_length").html(imgNum);
            })
        } else if (index == 7) {
            $("#file7").click();
            $("#file7").unbind().change(function (e) {
                var index = e.currentTarget.dataset.id;
                if ($('#file7').val() == '') {
                    return false;
                }
                20
                $(that).hide();
                var filePath = $(this).val();
                changeImg(e, filePath, index);

                imgNum++;
                if (imgNum < 8) {
                    $(".upload_img").eq(7).show();
                }
                $(".upload_img_length").html(imgNum);
            })
        } else if (index == 8) {
            $("#file8").click();
            $("#file8").unbind().change(function (e) {
                var index = e.currentTarget.dataset.id;
                if ($('#file8').val() == '') {
                    return false;
                }
                var filePath = $(this).val();
                changeImg(e, filePath, index);
                $(that).hide();
                imgNum++;
                $(".upload_img_length").html(imgNum);
            })
        }
    });

    function changeImg(e, filePath, index) {
        indexSet[index] = filePath;
        alert("被修改：" + index);
        var fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase();
        //检查后缀名
        if (!fileFormat.match(/.png|.jpg|.jpeg/)) {
            alert('文件格式必须为：png/jpg/jpeg');
            return;
        }
        //获取并记录图片的base64编码
        var reader = new FileReader();
        reader.readAsDataURL(e.target.files[0]);
        reader.onloadend = function () {
            // 图片的 base64 格式, 可以直接当成 img 的 src 属性值
            var dataURL = reader.result;
            // console.log(dataURL)
            // 显示图片
            var showHtml = `${$("#imgBox").html()}<div class="imgContainer" data-index=${index}><img src=${dataURL} onclick="imgDisplay(this)"><img onclick="removeImg(this,${index})"  class="imgDelete" src="../img/del_img.png" /></div>`
            $("#imgBox").html(showHtml);
        };
    }

    /**
     *移除图片的方法
     *
     */
    function removeImg(obj, index) {
        alert("被删除：" + index);
        indexSet[index] = '';
        for (var i = 0; i < $(".imgContainer").length; i++) {
            if ($(".imgContainer").eq(i).attr("data-index") == index) {
                $(".imgContainer").eq(i).remove();
            }
        }
        for (var i = 0; i < $(".upload_img").length; i++) {
            $(".upload_img").eq(i).hide();
            if ($(".upload_img").eq(i).attr("data-id") == index) {
                console.log($(".upload_img").eq(i).attr("data-id"))
                $(".upload_img").eq(i).show();
            }
        }
        imgNum--;
        $(".upload_img_length").html(imgNum);
    }

    function imgDisplay(obj) {    // 设定点击图片之后弹出显示图片详情的div
        var src = $(obj).attr("src");
        var imgHtml = `<div style="width:100%;height:100vh;overflow:auto;background:rgba(0,0,0,0.5);text-align:center;position: fixed;top:0;left:0;z-index:1000;display:flex;justify-content:center;align-items:center;">
                    <img src=${src} style="margin-top: 100px;width: 96%;margin-bottom: 100px;" alt="">
                    <p style="font-size: 50px;position: fixed;top: 30px;right: 30px;color: white;cursor: pointer;" onclick="closePicture(this)">×</p>
                  </div>`;
        $('body').append(imgHtml);
    }

    function closePicture(obj) {
        $(obj).parent("div").remove();
    }


    function doUpload() {                          // 组装上传信息
        var formData = new FormData();
        var userName = $("#userName").val();
        var userMobile = $("#userMobile").val();
        var json = {"userName": userName, "userMobile": userMobile};
        let stringify = JSON.stringify(json);
        console.log(json);
        formData.append("user",stringify);
        if (imgNum < 1) {
            alert("请至少上传一张图片！");
            return false;
        }

        console.log("要上传的集合是：" + JSON.stringify(indexSet));
        for (let i = 0; i < indexSet.length; i++) {
            if (indexSet[i] !== '' && indexSet[i] != null && indexSet[i] !== undefined) {
                console.log("最终要上传的文件index是：" + i + "文件路径是：" + indexSet[i]);
                formData.append("file", $('#file' + i)[0].files[0]);
            }
        }

        $.ajax({                                    // 上传图片
            url: '/files',
            type: 'post',
            data: formData,
            cache: false,
            processData: false,  	                //必须false才会避开jQuery对 formdata 的默认处理
            contentType: false,		                //必须false才会自动加上正确的Content-Type
            async: false
        }).done(function (res) {
            alert("上传成功！");
        }).fail(function (res) {
            alert("上传失败！");
        });
    }

</script>
</body>
</html>
